package me.caofeng.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import me.caofeng.enums.Role;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.omg.DynamicAny._DynEnumStub;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.util
 * @Description: json web token 工具类 ，
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-06-18 18:27
 * @Version: V1.0
 */
public class JwtUtil {
    private static Logger LOGGER = LogManager.getLogger(JwtUtil.class);

    private JwtUtil(){
        throw new IllegalArgumentException("工具类不能实例化");
    }
    /**
     * 生成jwt的密钥
     */
    private static String SECRET = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJNIiwic3ViIjoiZmpkbHNhZ2praGtoZ2RzZHMiLCJhZ2VudCI6InRlc3QgYWdlbnQgIiwiaXNzIjoidGllbml1IiwiZXhwIjoxNDkxNjQ0NTM5LCJpYXQiOjE0OTE2NDQ1Mjl9.UoghK92jqLKhlO8yUEerucH6v1SiYaFq3Xp8P3P2cOU";

    /**
     * @Author:曹峰 blog.caofeng.me
     * @Date: 2017/6/18 18:51
     * @Description: 创建jwt
     * @param phone 用户id
     * @param expire token有效期 ,单位 毫秒
     * @param userId 目标受众
     *
    */
    public static String createToken(String phone, long expire,String userId){
        String token = null;
        Date issuedTime = new Date() ;
        Date expireTime = new Date(System.currentTimeMillis() + expire) ;
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            token = JWT.create()
                    .withIssuedAt(issuedTime)
                    .withExpiresAt(expireTime)
                    .withAudience(userId)
                    .withSubject(phone)
                    .sign(algorithm);
        } catch (Exception e) {
            LOGGER.error(e);
        }
        return token;
    }

    /**
     * @Author:曹峰 blog.caofeng.me
     * @Date: 2017/6/18 22:54
     * @Description: 验证token
     * @param token token
     *
    */
    public static DecodedJWT verifyToken(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt;
        } catch (Exception e) {
            LOGGER.error(e);
        }
        return null;
    }

    public static void main(String[] args){
//        String  userId = "fsdfas";
//        long expire =  10 * 60 * 1000l;
//        Role role = Role.MEMBER;
//        String token = createToken(userId,expire,role);
//        LOGGER.debug(token);
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI1OWZkZDhiMjgxOTM0MjgxOGI5MWY1OTE4NWYxYzYwNSIsInN1YiI6IjE4NjEyNjkyNDU4IiwiZXhwIjoxNDk3ODU0NzY5LCJpYXQiOjE0OTc4NTQxNjl9.yB648IdmUtCg1LPomMHHq_V0cwb_WJwXNhlNDDJcG68";
        DecodedJWT jwt = verifyToken(token);
        LOGGER.debug(jwt.getAudience());
        LOGGER.debug(jwt.getSubject());
        LOGGER.debug(jwt.getExpiresAt());

    }

}
